package com.business.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ByteRedisUtil {

    private static RedisTemplate<String, byte[]> byteRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(ByteRedisUtil.class);
    //----------bitset---------////


    /**
     * bitset 添加byte[]
     *
     * @param redisKey
     * @return
     */
    public static void setBitData(String redisKey, byte[] obj) {
        try {
            byteRedisTemplate.opsForValue().set(redisKey, obj);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    /**
     * bitset
     *
     * @param redisKey
     * @return
     */
    public static byte[] getBitData(String redisKey) {
        try {
            byte[] bytes = byteRedisTemplate.opsForValue().get(redisKey);
            return bytes;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * bitset 添加
     *
     * @param redisKey
     * @return
     */
    public static Boolean setBit(String redisKey, Integer obj) {
        try {
            return byteRedisTemplate.opsForValue().setBit(redisKey, obj, true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * bitset 添加
     *
     * @param redisKey
     * @return
     */
    public static Boolean setBit(String redisKey, Integer obj, boolean flag) {
        try {
            return byteRedisTemplate.opsForValue().setBit(redisKey, obj, flag);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * bitset 总数
     *
     * @param redisKey
     * @return
     */
    public static long bitCount(final String redisKey) {
        try {
            return byteRedisTemplate.execute((RedisCallback<Long>) con -> {
                return con.bitCount(redisKey.getBytes());
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return 0;
    }

    @Resource(name = "byteRedisTemplate")
    public void setByteRedisTemplate(RedisTemplate<String, byte[]> r) {
        byteRedisTemplate = r;
    }

}
